import { Injectable } from '@nestjs/common';
import { Redis } from 'ioredis';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class RedisService {
  private redisClient: Redis;

  constructor(private readonly configService: ConfigService ) {
    this.redisClient = new Redis({
      host: this.configService.get('REDIS_HOST'),
      port: this.configService.get('REDIS_PORT'),
      password: this.configService.get('REDIS_PASSWORD'),
      db: this.configService.get('REDIS_DB'),
    });
  }

  // 设置缓存
  async set(key: string, value: string, expire: number = 60 * 60 * 24 * 7) {
    await this.redisClient.set(key, value, 'EX', expire);
  }

  // 获取缓存
  async get(key: string) {
    return await this.redisClient.get(key);
  }

  // 删除缓存
  async del(key: string) {
    await this.redisClient.del(key);
  }

  // 检查缓存是否存在
  async exists(key: string) {
    return await this.redisClient.exists(key);
  }

  // 关闭连接
  async close() {
    await this.redisClient.quit();
  }
}
